package com.gla.market.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gla.market.R;
import com.gla.market.SearchHistoryDatabase.PetShopDatabaseHelper;
import com.gla.market.SearchHistoryDatabase.TuiJian;
import com.gla.market.adapter.AfterSearchAdapter;
import com.gla.market.adapter.FYH_ShopAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Commodity;
import com.gla.market.entity.FYH_Shop;
import com.gla.market.entity.SearchBean;
import com.gla.market.entity.ShopItem;
import com.gla.market.fragments.HomePage;
import com.gla.market.utils.NetUtil;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;

import java.io.IOException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class BeforeSearchActivity extends AppCompatActivity implements View.OnClickListener, TencentLocationListener {

    private Context mContext; //定义一个自己的context
    private Button search; //搜索按钮
    private EditText in; //搜索框输入的内容
    private TextView history_1,history_2,history_3,history_4; //搜索历史
    private TextView find_1,find_2,find_3,find_4; //搜索发现
    private GridView shop_item_list;
    List<ShopItem> shopItemList = new ArrayList<>();  //适配器里的数据
    private AfterSearchAdapter shop_item_adapter; //适配器对象
    Double La,Lo; //经纬度

    private SharedPreferences sp;  //共享数据
    PetShopDatabaseHelper petShopDatabaseHelper; //数据库
    List<SearchBean> search_history;  //搜索历史
    List<Commodity> lists; //搜索发现
    String userId;
    Integer user_id;

    private TuiJian tuiJian;

    //用于从网络初始化UI的handler
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "请求数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    System.out.println(shopItemList);
                    //成功调用，到adapter赋值
                    shop_item_adapter = new AfterSearchAdapter(mContext,shopItemList,La,Lo);
                    shop_item_list.setAdapter(shop_item_adapter);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_before_search);
        //最上面搜索框
        search = findViewById(R.id.search_test_go);
        in = findViewById(R.id.search_test_in);
        //历史搜索
        history_1 = findViewById(R.id.search_history1);
        history_2 = findViewById(R.id.search_history2);
        history_3 = findViewById(R.id.search_history3);
        history_4 = findViewById(R.id.search_history4);
        //搜索发现
        find_1 = findViewById(R.id.search_find1);
        find_2 = findViewById(R.id.search_find2);
        find_3 = findViewById(R.id.search_find3);
        find_4 = findViewById(R.id.search_find4);
        mContext =this;
        System.out.println("控件初始化成功");

        sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        user_id = sp.getInt("user_id",0);;
        userId = user_id.toString();
        System.out.println("userId="+userId);
        petShopDatabaseHelper = new PetShopDatabaseHelper(this); //初始化数据库
        //获取所有的搜索历史
        initHistorySearch();

        //搜索发现调用推荐算法
        initSearchFind();


        //周边商铺,获取经纬度
        getLocation();

        //点击搜索按钮
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String text_in = in.getText().toString().trim();
                //搜索历史写入本地数据库
                searchOrupdataSQLite(text_in);

                Search(text_in);  //搜索

            }
        });

    }
    public void getLocation(){
        //获取定位,不可改动
        TencentLocationManager mLocationManager = TencentLocationManager.getInstance(mContext);
        mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
    }
    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        La = tencentLocation.getLatitude();
        Lo = tencentLocation.getLongitude();

        System.out.println("经纬度获取成功");
        initView(); //适配器初始化
        initData(tencentLocation.getLatitude(),tencentLocation.getLongitude()); //适配器数据初始化
    }
    @Override
    public void onStatusUpdate(String s, int i, String s1) { }


    //适配器初始化
    private void initView(){
        //绑定控件
        shop_item_list = findViewById(R.id.before_search_shop_item);

        //监听适配器列表
        shop_item_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShopItem shopItem = shopItemList.get(position);
                Integer shop_id = shopItem.getId();
                Intent intent = new Intent(BeforeSearchActivity.this, Shop_FYHActivity.class);
                intent.putExtra("id",shop_id + "");
                startActivity(intent);
            }
        });
    }

    //适配器数据初始化
    private void initData(double Latitude,double Longitude){

        //调用后端，获取json数据
        String url = Constants.BASE_URL + Constants.GET_SEARCH_URL + Constants.GET_NEAR_SHOP + "?latitude="+Latitude+"&longitude="+Longitude;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();

                        if (!object.getString("message").contains("JWT") && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            System.out.println("或取商品成功");
                            shopItemList = JSONArray.parseArray(array.toString(), ShopItem.class);
                            System.out.println(shopItemList);
                            System.out.println("赋值商品成功");
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );

//        shop_item_adapter = new AfterSearchAdapter(this,shopItemList);
//        shop_item_list.setAdapter(shop_item_adapter);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //搜索框搜索
            case R.id.search_test_back:
                finish();
                break;
            //点击搜索历史搜索
            case R.id.search_history1:
                String history1 = search_history.get(0).getKeyword();
                searchOrupdataSQLite(history1);
                Search(history1);
                break;
            case R.id.search_history2:
                String history2 = search_history.get(1).getKeyword();
                searchOrupdataSQLite(history2);
                Search(history2);
                break;
            case R.id.search_history3:
                String history3 = search_history.get(2).getKeyword();
                searchOrupdataSQLite(history3);
                Search(history3);
                break;
            case R.id.search_history4:
                String history4 = search_history.get(3).getKeyword();
                searchOrupdataSQLite(history4);
                Search(history4);
                break;


            case R.id.search_test_delete:
                //未完成，清除历史记录
                history_1.setText("");
                history_2.setText("");
                history_3.setText("");
                history_4.setText("");
                petShopDatabaseHelper.deleteUserAll(userId);
                break;

            //点击搜索发现搜索
            case R.id.search_find1:
                String find1 = lists.get(0).getName();
                searchOrupdataSQLite(find1);
                Search(find1);
                break;
            case R.id.search_find2:
                String find2 = lists.get(1).getName();
                searchOrupdataSQLite(find2);
                Search(find2);
                break;
            case R.id.search_find3:
                String find3 = lists.get(2).getName();
                searchOrupdataSQLite(find3);
                Search(find3);
                break;
            case R.id.search_find4:
                String find4 = lists.get(3).getName();
                searchOrupdataSQLite(find4);
                Search(find4);
                break;

        }
    }

    //搜索
    public void Search(String keyword){
        //未完成，跳转到相应页面intent
        Intent intent = new Intent(BeforeSearchActivity.this, AfterSearchActivity.class);
        intent.putExtra("keyword",keyword);
        startActivity(intent);
        //Toast.makeText(this, ""+keyword, Toast.LENGTH_SHORT).show();
    }

    //本地写数据库和修改数据库
    private void searchOrupdataSQLite(String text_in){
        //在这里写数据库
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        System.out.println(date);

        SearchBean searchBean = petShopDatabaseHelper.QueryFromKeyword(text_in,"1");
        System.out.println("这里"+searchBean);
        if(searchBean.getUserId()!=null && searchBean.getKeyword()!=null ){
            //有数据，改时间
            petShopDatabaseHelper.update(userId,text_in,date);
            System.out.println("有数据，修改成功");
        }else{
            //无数据，加入
            petShopDatabaseHelper.insert(userId,text_in,date);
            System.out.println("插入数据成功");
        }
    }

    //历史订单写入页面
    private void initHistorySearch(){
        search_history = petShopDatabaseHelper.getUserHistory(userId);
        Integer his_len = search_history.size();
        if(his_len==0){
            history_1.setText("");
            history_2.setText("");
            history_3.setText("");
            history_4.setText("");
        }
        if(his_len==1){
            String name0 = search_history.get(0).getKeyword();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";
            history_1.setText(name0);
            history_2.setText("");
            history_3.setText("");
            history_4.setText("");
        }
        if(his_len==2){
            String name0 = search_history.get(0).getKeyword();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";
            String name1 = search_history.get(1).getKeyword();
            if(name1.length() > 6) name1 =  name1.substring(0,6) + "...";
            history_1.setText(name0);
            history_2.setText(name1);
            history_3.setText("");
            history_4.setText("");
        }
        if(his_len==3){
            String name0 = search_history.get(0).getKeyword();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";
            String name1 = search_history.get(1).getKeyword();
            if(name1.length() > 6) name1 =  name1.substring(0,6) + "...";
            String name2 = search_history.get(2).getKeyword();
            if(name2.length() > 6) name2 =  name2.substring(0,6) + "...";
            history_1.setText(name0);
            history_2.setText(name1);
            history_3.setText(name2);
            history_4.setText("");
        }
        if(his_len>3){
            String name0 = search_history.get(0).getKeyword();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";
            String name1 = search_history.get(1).getKeyword();
            if(name1.length() > 6) name1 =  name1.substring(0,6) + "...";
            String name2 = search_history.get(2).getKeyword();
            if(name2.length() > 6) name2 =  name2.substring(0,6) + "...";
            String name3 = search_history.get(3).getKeyword();
            if(name3.length() > 6) name3 =  name3.substring(0,6) + "...";

            history_1.setText(name0);
            history_2.setText(name1);
            history_3.setText(name2);
            history_4.setText(name3);
        }
    }
    private void initSearchFind(){

        tuiJian = new TuiJian();
        lists = tuiJian.SearchFine(mContext,user_id); //发送context和user的id，id为Interge类型

        Integer len = lists.size();
        if(len==0){
            find_1.setText("");
            find_2.setText("");
            find_3.setText("");
            find_4.setText("");
        }
        if(len==1){
            String name0 = lists.get(0).getName();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";
            find_1.setText(name0);
            find_2.setText("");
            find_3.setText("");
            find_4.setText("");
        }
        if(len==2){
            String name0 = lists.get(0).getName();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";

            String name1 = lists.get(1).getName();
            if(name1.length() > 6) name1 =  name1.substring(0,6) + "...";
            find_1.setText(name0);
            find_2.setText(name1);
            find_3.setText("");
            find_4.setText("");
        }
        if(len==3){
            String name0 = lists.get(0).getName();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";

            String name1 = lists.get(1).getName();
            if(name1.length() > 6) name1 =  name1.substring(0,6) + "...";

            String name2 = lists.get(2).getName();
            if(name2.length() > 6) name2 =  name2.substring(0,6) + "...";

            find_1.setText(name0);
            find_2.setText(name1);
            find_3.setText(name2);
            find_4.setText("");
        }
        if(len>3){
            String name0 = lists.get(0).getName();
            if(name0.length() > 6) name0 =  name0.substring(0,6) + "...";

            String name1 = lists.get(1).getName();
            if(name1.length() > 6) name1 =  name1.substring(0,6) + "...";

            String name2 = lists.get(2).getName();
            if(name2.length() > 6) name2 =  name2.substring(0,6) + "...";
            String name3 = lists.get(3).getName();
            if(name3.length() > 6) name3 =  name3.substring(0,6) + "...";

            find_1.setText(name0);
            find_2.setText(name1);
            find_3.setText(name2);
            find_4.setText(name3);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

       initHistorySearch();
    }
}